/*****************************************************************************
*
*  PROJECT:     SlipStream
*               (Timer Classes)
*  LICENSE:     GNU General Public License v3 - http://www.gnu.org/licenses/gpl.html

*  DEVELOPERS:  Philip Farquharson	<B00137077@studentmail.uws.ac.uk>
*				John Gray			<B00145524@studentmail.uws.ac.uk>		
*				Zohaib Bhatti		<B00104280@studentmail.uws.ac.uk>
*				Euan Hislop			<B00138636@studentmail.uws.ac.uk>
*
*****************************************************************************/
#include "CTimerManager.h"

template<> CTimerManager * CSingleton< CTimerManager >::m_pSingleton = NULL;

CTimerManager::CTimerManager ( void ) {}
CTimerManager::~CTimerManager ( void ) 
{
	std::list<CTimer*>::const_iterator iter = timers.begin();
	for ( ; iter != timers.end (); ++iter )
	{
		CTimer* pTimer = static_cast < CTimer* > ( *iter );

		assert ( pTimer );

		// free our resources
		SAFE_DELETE( pTimer );
	}
}

CTimer* CTimerManager::createTimer( TimerCallback CallBack, unsigned int ms, int repeat, int value = -1 )
{
	CTimer* timer = new CTimer(CallBack, ms, repeat, value);
	timers.push_back ( timer );
	return timer;
}

void CTimerManager::Proc ()
{
	unsigned int currms = clock();
	std::list<CTimer*>::const_iterator iter = timers.begin();

	for ( ; iter != timers.end (); ++iter )
	{
		// Check the timing on the timers
		CTimer* pTimer = static_cast < CTimer* > ( *iter );

		assert ( pTimer );

		if ( currms >= pTimer->getStartTick() + pTimer->getMS() ) // tick
		{
			pTimer->Tick ();
			pTimer->setStartTick(currms);
		}

		// remove killed timers
		if ( pTimer->getTicked() == pTimer->getRepeat() && pTimer->getRepeat() != 0 )
		{
			deadpool.push_back ( pTimer );
		}

	}

	// clean the dead pool
	std::list<CTimer*>::const_iterator deaditer = deadpool.begin();

	for ( ; deaditer != deadpool.end (); ++deaditer )
	{
		CTimer* pTimer = static_cast < CTimer* > ( *deaditer );
		assert ( pTimer );

		timers.remove ( pTimer );
		SAFE_DELETE( pTimer );
	}
	deadpool.clear();
}